import express from 'express';
import multer from 'multer';
import path from 'path';

const router = express.Router();

// 配置multer用于文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/'); // 上传目录
  }, 
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});
const upload = multer({ storage: storage });

// 上传图片接口
router.post('/api/upload', upload.single('image'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ success: false, message: 'No file uploaded' });
  }
  // 返回图片访问URL
  const imageUrl = `/uploads/${req.file.filename}`;
  res.json({
    success: true,
    message: 'Upload success',
    data: { imageUrl }
  });
});

export default router;